<template>
  <base-modal :title="title" @closed="reset" :show.sync="sendMessageDialog" :width="width"
              class="biz-send-message-dialog">
    <el-form label-position="top" ref="form" :model="form" >
      <el-form-item :label="$t('component.bizSendMessage.label.recipient')">
        <el-radio-group v-model="form.isAllLm" @change="fetchCount" :disabled="pending">
          <el-radio label="0" :style="{ width: '120px'}">{{$t('component.bizSendMessage.contactRadio[0]')}}</el-radio>
          <el-radio label="1" :style="{ width: '120px'}">{{$t('component.bizSendMessage.contactRadio[1]')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('component.bizSendMessage.label.template')">
        <el-select v-model="form.smsTemplateId" :placeholder="$t('common.placeholder.selectSMStemplate')" style="width: 220px">
          <el-option v-for="item in messageTemplate" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('component.bizSendMessage.label.content')">
        <el-input type="textarea" v-model="template" rows="5" resize="none"></el-input>
      </el-form-item>
      <el-form-item :label="$t('component.bizSendMessage.label.sendTime')" :error="error">
        <div class="flex-x">
          <el-radio v-model="form.sendTimeType" :label="1" @change="sendTimeTypeChange">{{ $t('common.base.immediately') }}</el-radio>
          <el-radio class="mar-l-24" v-model="form.sendTimeType" :label="2" @change="sendTimeTypeChange">{{ $t('common.base.atRegularTime') }}</el-radio>
          <el-date-picker
            class="mar-l-12"
            popper-class="message-date-picker"
            v-show="form.sendTimeType === 2"
            v-model="form.sendTime"
            type="datetime"
            :placeholder="$t('common.placeholder.selectDateTime')"
            :picker-options="datePickerOption"
            default-time="12:00"
            format="yyyy-MM-dd HH:mm"
            value-format="timestamp"
          >
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item>
        <p v-if="type==='repeatPhone'">{{$t('component.bizSendMessage.sendStatic[0]', { count, repeatCount, effectiveCount})}}</p>
        <p v-else>{{$t('component.bizSendMessage.sendStatic[1]', { count })}}</p>
        <p>{{$t('component.bizSendMessage.sendStatic[2]', { smsRest })}}</p>
        <p>{{$t('component.bizSendMessage.sendStatic[3]')}}</p>
        <p>{{$t('component.bizSendMessage.sendStatic[4]')}}</p>
        <p>{{$t('component.bizSendMessage.sendStatic[5]')}}</p>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="sendMessageDialog = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit" :disabled="pending">{{$t('common.base.confirm')}}</el-button>
    </div>

  </base-modal>
</template>

<script>
import * as CustomerApi from '@src/api/CustomerApi.ts';
import i18n from '@src/locales';
import moment from 'moment'

export default {
  name: "biz-send-message",
  data: () => {
    return {
      form: {
        smsTemplateId: '',
        type: '',
        isAllLm: '0',
        sendTime: +new Date(),
        sendTimeType: 1,
      },
      count: 0,
      repeatCount: 0,
      effectiveCount: 0,
      sendMessageDialog: false,
      pending: false,
      messageTemplate: [],
      datePickerOption: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      error: '',
    }
  },
  props: {
    mode:{
      type:String,
      default:'customer'
    },
    title: {
      type: String,
      default: i18n.t('common.base.sendSMS')
    },
    width: {
      type: String,
      default: '600px'
    },
    selectedIds: {
      type: Array,
      default: () => ([]),
    },
    smsRest: {
      type: Number,
      default: 0,
    },
    type: {
      type: String,
      default: '',
    },
  },
  computed: {
    template() {
      return this.messageTemplate.filter(t => t.id === this.form.smsTemplateId)
        .map(t => t.allowContent).join('');
    },
  },
  mounted() {
    this.buildParams();
  },
  methods: {
    sendTimeTypeChange() {
      this.error = '';
    },
    async onSubmit() {
      const { sendTime, sendTimeType } = this.form;
      this.error = '';

      if (sendTimeType == 2) {
        if (!sendTime) {
          return this.error = i18n.t('common.validate.requiredSendTime');
        } else if(sendTime < +new Date()) {
          return this.error = i18n.t('common.validate.invalidSendTime');
        }
      }

      const params = this.buildParams();
      const maxCount = 100;

      if(params.type == '1' && this.count < maxCount) {
        return this.$platform.alert(i18n.t('component.bizSendMessage.submit.limitAlert', { maxCount }));
      }

      this.pending = true;
      let res
      if(this.mode==='customer'){
        res=await  CustomerApi.sendSmsBatch(params)
      }else{
        res=await  CustomerApi.productSendSmsBatch(params)
      }
       this.pending = false;
        if (res.status) return this.$platform.alert(res.message);
        this.sendMessageDialog = false;
        this.$platform.notification({
            title: i18n.t('common.base.tip.batchSendSMSSuccess'),
            type: 'success',
        });
    },
    openSendMessageDialog() {
      if (!this.selectedIds.length) {
        return this.$platform.alert(i18n.t('common.base.tip.selectSendSMSCustomer'));
      }
      this.sendMessageDialog = true;
      this.form.sendTime = +new Date()
      this.fetchCount();
      this.fetchTemplate();
    },
    async fetchCount() {
      this.pending = true;
      let res
      if(this.mode==='customer'){
          res=await CustomerApi.computeSendNum({ids: this.selectedIds,isAllLm: this.form.isAllLm})
      }else if(this.mode==='product'){
          res=await  CustomerApi.productComputeSendNum({ids: this.selectedIds,isAllLm: this.form.isAllLm})
      }
      if(this.type === 'repeatPhone'){
        const { effectiveCount,repeatCount } = res.data;
        this.effectiveCount = effectiveCount || 0;
        this.repeatCount = repeatCount || 0;
        this.count = effectiveCount + repeatCount || 0;
        this.pending = false;
      }else {
         this.count = res.data || 0;
         this.pending = false;
     }
    },
    fetchTemplate() {
      this.$http.get('/vipsms/getTemplates', {pageSize: '100', pageNum: '1',})
        .then(res => {
          if (res.status) {
            this.$platform.alert(i18n.t('common.base.tip.fetchSMSTemplateFail'));
          }
          // TODO 国际化 bell 通知判断中文
          this.messageTemplate = (res.data.list || [])
            .filter(t => (t.notice === '自定义通知' || t.notice === '客户体验调研通知' || t.type == 1) && t.status === 'pass_approval');
          if (this.messageTemplate.length) {
            this.form.smsTemplateId = this.messageTemplate[0].id;
          }

        })
        .catch(err => {
          console.error('fetchTemplate', err);
          this.$platform.alert(i18n.t('common.base.tip.fetchSMSTemplateError'));
        })
    },
    buildParams() {
      let {smsTemplateId, isAllLm, sendTime, sendTimeType} = this.form;

      // 选择立即时，发送时间为当前时间
      if (sendTimeType == 1) {
        sendTime = moment(+new Date()).valueOf();
      }

      const chooseTemplate = this.messageTemplate.filter(template => {
        return template.id == smsTemplateId;
      });

      const type = chooseTemplate.length ? (chooseTemplate[0].type || '') : '';

      return {
        smsTemplateId,
        isAllLm,
        type,
        // sendTime: formatDate(sendTime, 'YYYY-MM-DD HH:mm:ss'),
        sendTime: moment(sendTime).valueOf(),
        ids: this.selectedIds.join(','),
      }
    },
    reset() {

      if(this.type === 'repeatPhone'){
        this.count = 0;
        this.repeatCount = 0;
        this.effectiveCount = 0;
      }else {
        this.count = {
          default: {
            value: 0,
            loaded: false,
          },
          all: {
            value: 0,
            loaded: false,
          },
        };
      }

    }
  },
}
</script>

<style lang="scss">
  .biz-send-message-dialog {

    .base-modal-body {
      padding: 0 0 20px;
    }

    .el-form {
      padding: 0 30px;
      .el-form-item {
        margin: 10px 0;
      }

      label {
        margin: 0;
        font-weight: normal;
        &.mar-l-24 {
          margin-left: 24px;
        }
      }
      .el-radio {
        line-height: 32px;
      }
      .line {
        text-align: center;
      }
      p {
        margin: 0;
        line-height: 24px;
      }
    }

    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      padding: 10px 30px 0;
    }
  }
  .message-date-picker {
    .el-picker-panel__footer .el-button--text.el-picker-panel__link-btn {
      display: none;
    }
  }
</style>
